package com.example.orchid.paper.activity;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;

import com.example.orchid.paper.Constants;
import com.example.orchid.paper.R;
import com.example.orchid.paper.fragment.NewsListFragment;
import com.example.orchid.paper.task.MyAsyncTask;
import com.example.orchid.paper.task.OfflineDownloadTask;
import com.example.orchid.paper.task.ResponseListener;
import com.example.orchid.paper.util.DateUtils;
import com.example.orchid.paper.util.NetWorkHelper;
import com.example.orchid.paper.util.PreferencesUtils;

import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.ShareSDK;


public class MainActivity extends BaseActivity implements ResponseListener {

    private static final int REQUESTCODE_SETTING = 8009;

    private FrameLayout mFrameLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFrameLayout = (FrameLayout) findViewById(R.id.container);
        Fragment fragment1 = getFragment();
        if (fragment1 != null) {
            getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
        }


        // WIFI下自动开启离线
        if (NetWorkHelper.isWifi(this) && !PreferencesUtils.getBoolean(mInstance, DateUtils.getCurrentDate(), false)) {
            startOfflineDownload();
        }


    }

    /**
     * 开始离线下载
     */
    private void startOfflineDownload() {
        String getLatestUrl = Constants.Url.URL_LATEST;
        String todayUrl = Constants.Url.URLDEFORE + DateUtils.getCurrentDate(DateUtils.YYYYMMDD);
        String yesterdayUrl = Constants.Url.URLDEFORE + DateUtils.getYesterdayDate(DateUtils.YYYYMMDD);
        String theDayBeforeYesterdayUrl = Constants.Url.URLDEFORE + DateUtils.getTheDayBeforeYesterday(DateUtils.YYYYMMDD);

        String[] urls = {getLatestUrl, todayUrl, yesterdayUrl, theDayBeforeYesterdayUrl};
        for (String url : urls) {
            ResponseListener listener = url.equals(getLatestUrl) ? this : null;
            new OfflineDownloadTask(this, listener).executeOnExecutor(MyAsyncTask.DOWNLOAD_THREAD_POOL_EXECUTOR, url);
        }
    }

    @Override
    protected Fragment getFragment() {
        return new NewsListFragment();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_download:
                startOfflineDownload();
                return true;
            case R.id.action_favorite:
                startActivity(new Intent(this, FavoriteActivity.class));
                return true;
            case R.id.action_setting:
                startActivityForResult(new Intent(this, SettingsActivity.class), REQUESTCODE_SETTING);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        ShareSDK.stopSDK(this);
        super.onDestroy();
    }


    @Override
    public void onPreExecute() {
        Snackbar.make(mFrameLayout, R.string.offline_download_doing, Snackbar.LENGTH_LONG).show();
    }

    @Override
    public void onPostExecute(String content) {
        if (!TextUtils.isEmpty(content) && content.equals("success")) {

            PreferencesUtils.putBoolean(mInstance, DateUtils.getCurrentDate(), true);
            Snackbar.make(mFrameLayout, R.string.offline_download_done, Snackbar.LENGTH_LONG).show();

        } else {
            Snackbar.make(mFrameLayout, R.string.offline_download_fail, Snackbar.LENGTH_LONG).show();
        }
    }

    @Override
    public void onProgressUpdate(String value) {

    }

    @Override
    public void onFail(Exception e) {
        if (!isFinishing()) {
            Snackbar.make(mFrameLayout, R.string.offline_download_fail, Snackbar.LENGTH_LONG).show();
        }
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); //调用双击退出函数
        } else {
            return false;
        }
        return false;
    }

    private static Boolean isExit = false;

    /**
     * 双击退出函数
     */
    private void exitBy2Click() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true;// 准备退出
            Snackbar.make(mFrameLayout, "再按一次退出程序", Snackbar.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;// 取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }

    }
}
